//
//  QZHttpBaseModel.swift
//  YsCalendar
//
//  Created by 于洪礼 on 16/3/23.
//
//

//import UIKit
import AFNetworking
//import RealReachability

//成功闭包(Json)
typealias httpSuccessJsonData = (_ data:JSON)->Void
//成功闭包(data)
typealias httpSuccessData = (_ data:Data,_ type:String?)->Void
//错误闭包
typealias httpError = (_ error:NSError)->Void

class QZHttpBaseManager: NSObject {
    let strUrl:String
//    lazy var param:[String:Any] = {
//        return ["telephoneType":"1", "version":APIVersion,"clientVersion":LoginUserModel.shareInstance.bundleVersion,"userId":LoginUserModel.shareInstance.userId]
//        return [:]
//    }()
    var param:[String:Any] = [:]
    var acceptType: String = ""
    init(url:String){
//        if !url.hasPrefix("http"){
//            strUrl = YsHostURL + url
//        }else{
            strUrl = url
//        }
        super.init()
    }
    
    //添加param
    func addParam(_ dic:[String:Any]){
        for (key,value) in dic{
            self.param.updateValue(value, forKey: key)
        }
    }
    
    //请求JSON数据
    func getJsonData(_ success:httpSuccessJsonData?,faile:httpError?){
        
        #if !QZRELEASE
            var totalUrl = ""
            totalUrl += "\(self.strUrl)?"
            for (key, value) in self.param {
                totalUrl += "\(key)=\(value)&"
            }
            let endIndex = totalUrl.index(before: totalUrl.endIndex)
            totalUrl.remove(at: endIndex)
//            qzprint("totalUrl",totalUrl)
        #endif
        
        let url = self.strUrl
        
        let manager = AFHTTPSessionManager()
        manager.responseSerializer = AFHTTPResponseSerializer()
        //设置超时时间
        manager.requestSerializer.timeoutInterval = 10.0
        manager.post(self.strUrl, parameters: self.param, progress: nil, success: { (task, responseObject) in
            

            let resultData = JSON(data: responseObject as! Data, options: JSONSerialization.ReadingOptions.mutableContainers, error: nil)
//            qzprint("resultData====:\(resultData)")
            
            if resultData["Result"].int == 1 {
                if let successed = success {
                    successed(resultData)
                }
            }else{

                if let failure = faile{
                    let error = NSError(domain: url, code: -3, userInfo: ["notWork":resultData["MessageInfo"].stringValue])
                    failure(error)
                }
            }
            
            
        }) { (task, error) in
//            qzprint("error:=========\(error)")
            if let failure = faile{
                let error = NSError(domain: url, code: -3, userInfo: ["notWork":"你的网络不太给力哦~"])
                failure(error)
            }
        }
        
        
        
    }
    
    func getMethodJsonData(_ success:httpSuccessJsonData?,faile:httpError?){
        
        #if !QZRELEASE
            var totalUrl = ""
            totalUrl += "\(self.strUrl)?"
            for (key, value) in self.param {
                totalUrl += "\(key)=\(value)&"
            }
            let endIndex = totalUrl.index(before: totalUrl.endIndex)
            totalUrl.remove(at: endIndex)
            //            qzprint("totalUrl",totalUrl)
        #endif
        
        let url = self.strUrl
        
        let manager = AFHTTPSessionManager()
        let coder = NSCoder()
        manager.responseSerializer = AFHTTPResponseSerializer()
        manager.responseSerializer.acceptableContentTypes = ["text/html","text/json","application/json","text/javascript"]
        //设置超时时间
        manager.requestSerializer.timeoutInterval = 10.0
        manager.get(self.strUrl, parameters: self.param, progress: nil, success: { (task, responseObject) in
            
            
            let resultData = JSON(data: responseObject as! Data, options: JSONSerialization.ReadingOptions.mutableContainers, error: nil)
            print("resultData====:\(resultData)")
            
//            if resultData["Result"].int == 1 {
//                if let successed = success {
//                    successed(resultData)
//                }
//            }else{
//
//                if let failure = faile{
//                    let error = NSError(domain: url, code: -3, userInfo: ["notWork":resultData["MessageInfo"].stringValue])
//                    failure(error)
//                }
//            }
//
            if let successed = success {
                successed(resultData)
            }
            
        }) { (task, error) in
            print("error:=========\(error)")
            if let failure = faile{
                let error = NSError(domain: url, code: -3, userInfo: ["notWork":"你的网络不太给力哦~"])
                failure(error)
            }
        }
        
    }
    
    
    //请求data数据
    func getData(_ success:httpSuccessData?,faile:httpError?){
        
        let manager = AFHTTPSessionManager()
        //设置超时时间
        manager.requestSerializer.timeoutInterval = 10.0
        //以服务器返回的格式接收
        manager.responseSerializer = AFHTTPResponseSerializer()
        manager.post(self.strUrl, parameters: self.param, progress: nil, success: { (task, responseObject) in
            
            if let successed = success {
                successed(responseObject as! Data , task.response?.mimeType)
            }
            
            
        }) { (task, error) in
            
            if let failure = faile{
                let error = NSError(domain: self.strUrl, code: -3, userInfo: ["notWork":"你的网络不太给力哦~"])
                failure(error)
            }
        }
        
    }
    
    
//    //上传图片
//    func uploadData(_ datas:[Data],success:httpSuccessJsonData?,faile:httpError?){
//        qzprint("PicUrl",self.strUrl)
//        qzprint("PicParam",self.param)
//
//        let manager = AFHTTPSessionManager()
//        manager.responseSerializer = AFHTTPResponseSerializer()
//        manager.post(self.strUrl, parameters: self.param, constructingBodyWith: { (formData) in
//
//            var i = 0
//            let fileNames = ["file","fileb","filec"]
//            let names = ["image.png","imageb.png","imagec.png"]
//            for data in datas{
//
//                formData.appendPart(withFileData: data, name: names[i], fileName: fileNames[i], mimeType: "image/png")
//                i += 1
//            }
//
//
//
//        }, progress: nil, success: { (task, responseObject) in
//
//            let resultData = JSON(data: responseObject as! Data, options: JSONSerialization.ReadingOptions.mutableContainers, error: nil)
//            if resultData["Result"].int == 1 {
//                if let successed = success {
//                    successed(resultData)
//                }
//
//            }else{
//                if let failure = faile{
//                    let error = NSError(domain: self.strUrl, code: -3, userInfo: ["notWork":resultData["MessageInfo"].stringValue])
//                    failure(error)
//                }
//            }
//
//        }) { (task, error) in
//            if let failure = faile{
//                let errore = NSError(domain: self.strUrl, code: -3, userInfo: ["notWork":"上传失败"])
//                failure(errore)
//            }
//        }
//
//    }
//
//
//    //七牛上传图片
//    func uploadQiniuData(_ data:Data,success:httpSuccessJsonData?,faile:httpError?){
//
//        let manager = AFHTTPSessionManager()
//        manager.responseSerializer = AFHTTPResponseSerializer()
//        manager.post(self.strUrl, parameters: self.param, constructingBodyWith: { (formData) in
//
//            formData.appendPart(withFileData: data, name: "file", fileName: "image.png", mimeType: "image/png")
//
//
//        }, progress: nil, success: { (task, responseObject) in
//
//            let resultData = JSON(data: responseObject as! Data, options: JSONSerialization.ReadingOptions.mutableContainers, error: nil)
//            success?(resultData)
//
//
//        }) { (task, error) in
//            if let failure = faile{
//                let errore = NSError(domain: self.strUrl, code: -3, userInfo: ["notWork":"上传失败"])
//                failure(errore)
//            }
//        }
//
//        qzprint("QiniuUrl",self.strUrl)
//        qzprint("QiniuParam",self.param)
//
//    }
//
//
//    //给七牛上传音频
//    func updteToQiniu(with filePath: URL, success:httpSuccessJsonData?, faile:httpError?) {
//
//        let manager = AFHTTPSessionManager()
//        manager.responseSerializer = AFHTTPResponseSerializer()
//        let surffix = filePath.absoluteString.substring(from: filePath.absoluteString.index(filePath.absoluteString.endIndex, offsetBy: -4))
//        qzprint("surffix  -> \(surffix)")
//        manager.post(self.strUrl, parameters: self.param, constructingBodyWith: { (formData) in
//
//            do {
//                let datas = try Data(contentsOf: filePath)
//                formData.appendPart(withFileData: datas, name: "file", fileName: "voice.\(surffix)", mimeType: "application/octet-stream")
//            }catch let error as NSError {
//                qzprint("error --> \(error)")
//            }
//
//
//        }, progress: nil, success: { (task, responseObject) in
//
//            let resultData = JSON(data: responseObject as! Data, options: JSONSerialization.ReadingOptions.mutableContainers, error: nil)
//            success?(resultData)
//
//
//        }){  (task, error) in
//            qzprint("error --> \(error)")
//            if let failure = faile{
//                //let errore = NSError(domain: self.strUrl, code: -3, userInfo: ["notWork":"上传失败"])
//                failure(error as NSError)
//            }
//        }
//
//    }
//
}

